package com.exmaple.lemlin.ui.activity;

import android.app.Activity;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Vibrator;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.design.internal.BottomNavigationItemView;
import android.support.design.internal.BottomNavigationMenuView;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.NotificationCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;

import com.ashokvarma.bottomnavigation.BottomNavigationBar;
import com.ashokvarma.bottomnavigation.BottomNavigationItem;
import com.ashokvarma.bottomnavigation.ShapeBadgeItem;
import com.ashokvarma.bottomnavigation.TextBadgeItem;
import com.exmaple.lemlin.R;
import com.exmaple.lemlin.app.APPIM;
import com.exmaple.lemlin.app.Constants;
import com.exmaple.lemlin.entity.ChatMessage;
import com.exmaple.lemlin.entity.ChatRecord;
import com.exmaple.lemlin.entity.ChatRecordDao;
import com.exmaple.lemlin.entity.FriendGood;
import com.exmaple.lemlin.entity.FriendGoodDao;
import com.exmaple.lemlin.mvp.presenter.MainPresenter;
import com.exmaple.lemlin.mvp.view.IMainView;
import com.exmaple.lemlin.ui.abstracts.AbstractBaseActivity;
import com.exmaple.lemlin.ui.adapter.MainPagerAdapter;
import com.exmaple.lemlin.ui.fragment.MainChatFragment;
import com.exmaple.lemlin.ui.fragment.MainFindFragment;
import com.exmaple.lemlin.ui.fragment.MainFriendFragment;
import com.exmaple.lemlin.ui.fragment.MainMineFragment;
import com.exmaple.lemlin.utils.JsonUtils;
import com.exmaple.lemlin.utils.LogUtils;
import com.exmaple.lemlin.utils.ToastUtil;
import com.exmaple.lemlin.xmpp.XmppConnection;

import org.greenrobot.eventbus.EventBus;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.roster.RosterEntry;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import io.reactivex.Notification;
import io.reactivex.Observable;
import io.reactivex.functions.Consumer;

public class MainActivity extends AbstractBaseActivity<MainPresenter> implements IMainView, BottomNavigationBar.OnTabSelectedListener, ViewPager.OnPageChangeListener {

    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.view_pager)
    ViewPager viewPager;
    @BindView(R.id.bottom_navigation_bar)
    BottomNavigationBar navigationBar;

    private MainPagerAdapter pageAdapter;

    private TextBadgeItem chatBadgeItem, friendBadgeItem, findBadgeItem, mineBadgeItem;
    private int countChatBadge = 0, countFriendBadge = 0;

    private OnMainChatListener mOnMainChatListener = null;
    private OnMainFriendListener mOnMainFriendListener = null;
    private OnMainMineListener mOnMainMineListener = null;

    @Override
    public void onAttachFragment(Fragment fragment) {
        try {
            if (fragment instanceof MainFriendFragment) {
                mOnMainFriendListener = (OnMainFriendListener) fragment;
            } else if (fragment instanceof MainChatFragment) {
                mOnMainChatListener = (OnMainChatListener) fragment;
            }
        } catch (Exception e) {
            throw new ClassCastException(this.toString() + " must implement OnMainListener");
        }
        super.onAttachFragment(fragment);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    protected void initView() {

        setSupportActionBar(toolbar);

        List<Fragment> fragments = new ArrayList<>();
        fragments.add(new MainChatFragment());
        fragments.add(new MainFriendFragment());
        fragments.add(new MainFindFragment());
        fragments.add(new MainMineFragment());
        pageAdapter = new MainPagerAdapter(getSupportFragmentManager(), fragments);
        viewPager.addOnPageChangeListener(this);
        viewPager.setOffscreenPageLimit(fragments.size());
        viewPager.setAdapter(pageAdapter);

        List<ChatRecord> records = APPIM.getDaoSession().getChatRecordDao().loadAll();
        for (ChatRecord record : records) {
            countChatBadge = countChatBadge + record.getLastMsgCount();
        }
        chatBadgeItem = new TextBadgeItem()
                .setBackgroundColorResource(R.color.red)
                .setHideOnSelect(false);
        if (countChatBadge != 0) {
            chatBadgeItem.setText(String.valueOf(countChatBadge));
        } else {
            chatBadgeItem.hide();
        }

        countFriendBadge = APPIM.getDaoSession().getFriendGoodDao().queryBuilder().where(FriendGoodDao.Properties.Sub.eq("none")).list().size();
        friendBadgeItem = new TextBadgeItem()
                .setBackgroundColorResource(R.color.red)
                .setHideOnSelect(false);
        if (countFriendBadge != 0) {
            friendBadgeItem.setText(String.valueOf(countFriendBadge));
        } else {
            friendBadgeItem.hide();
        }

        findBadgeItem = new TextBadgeItem()
                .setBackgroundColorResource(R.color.red)
                .setHideOnSelect(false)
                .hide();
        mineBadgeItem = new TextBadgeItem()
                .setBackgroundColorResource(R.color.red)
                .setHideOnSelect(false)
                .hide();
        navigationBar.addItem(new BottomNavigationItem(R.drawable.ic_nv_chat, ("聊天")).setBadgeItem(chatBadgeItem))
                .addItem(new BottomNavigationItem(R.drawable.ic_nv_friend, ("联系人")).setBadgeItem(friendBadgeItem))
                .addItem(new BottomNavigationItem(R.drawable.ic_nv_find, ("发现")).setBadgeItem(findBadgeItem))
                .addItem(new BottomNavigationItem(R.drawable.ic_nv_mine, ("我的")).setBadgeItem(mineBadgeItem))
                .setTabSelectedListener(this)
                .setFirstSelectedPosition(0)
                .initialise();
    }

    @Override
    protected void initPresenter() {
        mPresenter = new MainPresenter((this), (this));
        mPresenter.allFriendGoods();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!mPresenter.isAuthenticated()) {
            Intent intent = new Intent(this, AccessActivity.class);
            startActivity(intent);
            finish();
        }
    }

    @Override
    protected void onRestart() {
        super.onRestart();

        countFriendBadge = APPIM.getDaoSession().getFriendGoodDao().queryBuilder().where(FriendGoodDao.Properties.Sub.eq("none")).list().size();
        if (countFriendBadge == 0) {
            friendBadgeItem.hide();
        } else {
            friendBadgeItem.show();
            friendBadgeItem.setText(String.valueOf(countFriendBadge));
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == Activity.RESULT_OK) {
            int count = data.getIntExtra(Constants.BUNDLE_KEY_COUNT_UNREAD, 0);
            if (count != 0) {
                String userName = data.getStringExtra(Constants.BUNDLE_KEY_USER_NAME);
                ChatRecordDao recordDao = APPIM.getDaoSession().getChatRecordDao();
                ChatRecord record = recordDao.queryBuilder()
                        .where(ChatRecordDao.Properties.Name.eq(userName)).unique();
                record.setLastMsgCount(0);
                recordDao.update(record);

                if (mOnMainChatListener != null) {
                    mOnMainChatListener.onChatRecord(recordDao.queryBuilder()
                            .orderDesc(ChatRecordDao.Properties.LastMsgTime).list());
                }

                countChatBadge = countChatBadge - count;
                chatBadgeItem.setText(String.valueOf(countChatBadge));
                if (countChatBadge == 0) {
                    chatBadgeItem.hide();
                }
            }
        }
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.top_main_nav_menu, menu);
        return true;
    }


    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_addition:
                Intent intent = new Intent((this), FriendActivity.class);
                startActivity(intent);
                break;
            case R.id.action_scan:
                ToastUtil.showShort(this,"功能未开放");
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onTabSelected(int position) {

        switch (position) {
            case 0:
                toolbar.setTitle("聊天");
                viewPager.setCurrentItem(0);
                break;
            case 1:
                toolbar.setTitle("好友");
                viewPager.setCurrentItem(1);
                break;
            case 2:
                toolbar.setTitle("发现");
                viewPager.setCurrentItem(2);
                break;
            case 3:
                toolbar.setTitle("我的");
                viewPager.setCurrentItem(3);
                break;
            default:
                break;
        }
    }

    @Override
    public void onTabUnselected(int position) {

    }

    @Override
    public void onTabReselected(int position) {

    }

    @Override
    public void onPageScrolled(int i, float v, int i1) {

    }

    @Override
    public void onPageSelected(int i) {
        navigationBar.selectTab(i);
        switch (i) {
            case 0:
                toolbar.setTitle("聊天");
                break;
            case 1:
                toolbar.setTitle("联系人");
                break;
            case 2:
                toolbar.setTitle("发现");
                break;
            case 3:
                toolbar.setTitle("我的");
                break;
            default:
                break;
        }
    }

    @Override
    public void onPageScrollStateChanged(int i) {

    }

    @Override
    public void onEventMainThread(ChatMessage message) {
        super.onEventMainThread(message);
        if (!message.getFrom().equals(APPIM.getLoginUser().asBareJid().getLocalpartOrNull().intern())) {
            if (chatBadgeItem.isHidden())
                chatBadgeItem.show();
            countChatBadge = countChatBadge + 1;
            chatBadgeItem.setText(String.valueOf(countChatBadge));
        }
        if (mOnMainChatListener != null) {
            mOnMainChatListener.onChatRecord(APPIM.getDaoSession().getChatRecordDao().queryBuilder()
                    .orderDesc(ChatRecordDao.Properties.LastMsgTime).list());
        }
    }

    @Override
    public void onEventMainThread(FriendGood friend) {
        super.onEventMainThread(friend);
        if (friend.getSub().equals("both")) {
            if (mOnMainFriendListener != null) {
                mOnMainFriendListener.onFriendGood(friend);
            }
        } else {
            countFriendBadge = countFriendBadge + 1;
            if (friendBadgeItem.isHidden())
                friendBadgeItem.show();
            friendBadgeItem.setText(String.valueOf(countFriendBadge));
        }
    }

    @Override
    public void onFriendGood(FriendGood friendGood) {
        if (mOnMainFriendListener != null) {
            mOnMainFriendListener.onFriendGood(friendGood);
        }
    }


    public interface OnMainChatListener {
        void onChatRecord(List<ChatRecord> records);
    }

    public interface OnMainFriendListener {
        void onFriendGood(FriendGood friendGood);
    }

    public interface OnMainMineListener {

    }

}
